package cn.imatu.framework.ip2region.handler;

import cn.imatu.framework.ip2region.model.AddressInfo;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;

/**
 * @author shenguangyang
 */
@Slf4j
public class Geoip2Impl implements Ip2RegionHandler {
    private final DatabaseReader reader;

    public Geoip2Impl(DatabaseReader reader) {
        this.reader = reader;
    }

    /**
     * 获得详细地址
     */
    @Override
    public AddressInfo getAddress(String ipv4) throws Exception {
        try {
            if (StringUtils.isEmpty(ipv4)) {
                return new AddressInfo();
            }
            InetAddress inetAddress = InetAddress.getByName(ipv4);
            CityResponse cityResponse = reader.city(inetAddress);
            return AddressInfo.builder()
                .city(cityResponse.getCity().getNames().get("zh-CN"))
                .province(cityResponse.getMostSpecificSubdivision().getNames().get("zh-CN"))
                .country(cityResponse.getCountry().getNames().get("zh-CN"))
                .longitude(cityResponse.getLocation().getLongitude())
                .latitude(cityResponse.getLocation().getLongitude())
                .build();
        } catch (Exception e) {
            log.error("error: {}", e.getMessage());
        }
        return null;
    }
}
